package com.egao.common.module.pepesi.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egao.common.core.utils.ExcelUtils;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.module.pepesi.entity.PepsiStudentExcel;
import com.egao.common.module.pepesi.entity.vo.PepsiTeacherVO;
import com.egao.common.module.pepesi.mapper.PepsiTeacherMapper;
import com.egao.common.module.pepesi.service.PepsiStudentService;
import com.egao.common.module.pepesi.service.PepsiTeacherService;

import com.egao.common.module.student.service.impl.StudentServiceImpl;
import com.egao.common.module.system.constants.DictConstants;
import com.egao.common.module.system.service.DictService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static cn.hutool.core.util.NumberUtil.roundStr;

/**
 * 管理端学生的一百件事接口实现类
 *
 * @author pyx
 * @date 2021/5/13
 */
@Service
public class PepsiTeacherServiceImpl extends ServiceImpl<PepsiTeacherMapper, PepsiTeacherVO> implements PepsiTeacherService {
    @Autowired
    private PepsiStudentService pepsiStudentService;
    @Autowired
    private DictService dictService;
    private final Logger logger = LoggerFactory.getLogger(StudentServiceImpl.class.getName());

    @Override
    public List<PepsiTeacherVO> listPage(PageParam<PepsiTeacherVO> pageParam) {
        return baseMapper.listPage(pageParam);
    }


    @Override
    public JsonResult pepsiStudentData(Integer studentId, Integer finishState) {
        return pepsiStudentService.pepsiData(studentId, finishState);
    }

    @Override
    public void exportExcel(Map<String, Object> page, HttpServletResponse response) {
        List<PepsiStudentExcel> list = baseMapper.listExcel(page);

        for (PepsiStudentExcel item : list) {
            item.setXb(dictService.cacheLabel(DictConstants.TYPE_XB, item.getXb()));
            item.setXl(dictService.cacheLabel(DictConstants.TYPE_XL, item.getXl()));
        }

        ExcelWriter writer = ExcelUtil.getWriter(true);

        excelAddHeaderAlias(writer);

        writer.write(list, true);

        // 设置列自适应宽 必须在write以后
        ExcelUtils.autoColumnMaxSizeAll(writer.getSheet());

        String fileName = "pepsi-" + DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN) + ".xlsx";

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        try {
            OutputStream out = response.getOutputStream();
            writer.flush(out, true);
            writer.close();
            IoUtil.close(out);
        } catch (IOException e) {
            writer.close();
            logger.error("导出失败 - StudentPovertyServiceImpl - exportExcel", e);
        } finally {
            writer.close();
        }
    }

    @Override
    public JsonResult pepsiStatistics(Map<String, Object> page) {

        List<PepsiTeacherVO> list = baseMapper.pepsiStatistics(page);

        int upperQuartile = 0;
        int median = 0;
        int lowerQuartile = 0;

        for (PepsiTeacherVO pepsiTeacherVO : list) {
            if (pepsiTeacherVO.getFinishCount() >= 25 && pepsiTeacherVO.getFinishCount() < 50) {
                upperQuartile++;
            } else if (pepsiTeacherVO.getFinishCount() >= 50 && pepsiTeacherVO.getFinishCount() < 75) {
                median++;
            } else if (pepsiTeacherVO.getFinishCount() >= 75) {
                lowerQuartile++;
            }
        }

        double upperDouble = ((double) upperQuartile / list.size() * 100);
        double medianDouble = ((double) median / list.size() * 100);
        double lowerDouble = ((double) lowerQuartile / list.size() * 100);
        if (upperDouble > 0 && upperDouble < 0.01) {
            upperDouble = 0.01;
        }
        if (medianDouble > 0 && medianDouble < 0.01) {
            medianDouble = 0.01;
        }
        if (lowerDouble > 0 && upperDouble < 0.01) {
            lowerDouble = 0.01;
        }
        String upperStatistics = roundStr(upperDouble, 2);
        String medianStatistics = roundStr(medianDouble, 2);
        String lowerStatistics = roundStr(lowerDouble, 2);

        return JsonResult.ok().put("upperStatistics", upperStatistics).put("medianStatistics", medianStatistics).put("lowerStatistics", lowerStatistics);
    }

    /**
     * 为导出对象设置别名和排序 排序顺序为add顺序
     *
     * @param writer ExcelWriter
     */
    public void excelAddHeaderAlias(ExcelWriter writer) {
        writer.addHeaderAlias("yearId", "毕业年份");
        writer.addHeaderAlias("xm", "姓名");
        writer.addHeaderAlias("xb", "性别");
        writer.addHeaderAlias("xl", "学历");
        writer.addHeaderAlias("xh", "学号");
        writer.addHeaderAlias("college", "学院");
        writer.addHeaderAlias("major", "专业");
        writer.addHeaderAlias("finishCount", "完成个数");
        writer.addHeaderAlias("noFinishCount", "未完成个数");
        writer.addHeaderAlias("updateTime", "最后一次修改时间");
    }

}
